package com.bank.controller;

import com.bank.common.Result;
import com.bank.entity.CardInfo;
import com.bank.mapper.CardInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 银行卡控制器
 */
@RestController
@RequestMapping("/api/card")
public class CardInfoController {

    @Autowired
    private CardInfoMapper cardInfoMapper;

    /**
     * 查询所有银行卡信息
     */
    @GetMapping("/list")
    public Result<List<CardInfo>> list() {
        return Result.success(cardInfoMapper.findAll());
    }

    /**
     * 根据卡号查询银行卡信息
     */
    @GetMapping("/{cardId}")
    public Result<CardInfo> getById(@PathVariable("cardId") String cardId) {
        return Result.success(cardInfoMapper.findById(cardId));
    }

    /**
     * 根据客户ID查询银行卡信息
     */
    @GetMapping("/customer/{customerId}")
    public Result<List<CardInfo>> getByCustomerId(@PathVariable("customerId") Long customerId) {
        return Result.success(cardInfoMapper.findByCustomerId(customerId));
    }

    /**
     * 生成符合格式的银行卡号
     * 格式为：10103576 + 8位随机数字
     * @return 生成的银行卡号
     */
    private String generateCardId() {
        StringBuilder cardId = new StringBuilder("10103576");
        Random random = new Random();

        // 生成8位随机数字
        for (int i = 0; i < 8; i++) {
            cardId.append(random.nextInt(10));
        }

        return cardId.toString();
    }

    /**
     * 新增银行卡信息
     */
    @PostMapping
    public Result<Void> add(@RequestBody CardInfo cardInfo) {
        // 自动生成银行卡号
        String cardId = generateCardId();
        // 检查卡号是否已存在
        while (cardInfoMapper.findById(cardId) != null) {
            // 如果已存在则重新生成
            cardId = generateCardId();
        }
        cardInfo.setCardID(cardId);

        // 默认密码888888
        if (cardInfo.getPass() == null || cardInfo.getPass().isEmpty()) {
            cardInfo.setPass("888888");
        }

        // 默认币种RMB
        if (cardInfo.getCurID() == null || cardInfo.getCurID().isEmpty()) {
            cardInfo.setCurID("RMB");
        }

        // 默认未挂失
        if (cardInfo.getIsReportLoss() == null || cardInfo.getIsReportLoss().isEmpty()) {
            cardInfo.setIsReportLoss("否");
        }

        // 自动设置开户时间为当前时间
        cardInfo.setOpenDate(java.time.LocalDateTime.now());

        // 余额=开户金额
        cardInfo.setBalance(cardInfo.getOpenMoney());

        if (cardInfoMapper.insert(cardInfo) > 0) {
            return Result.success();
        }
        return Result.error("新增失败");
    }

    /**
     * 修改银行卡信息
     */
    @PutMapping
    public Result<Void> update(@RequestBody CardInfo cardInfo) {
        if (cardInfoMapper.update(cardInfo) > 0) {
            return Result.success();
        }
        return Result.error("修改失败");
    }

    /**
     * 挂失银行卡
     */
    @PostMapping("/report-loss")
    public Result<Void> reportLoss(@RequestBody Map<String, String> params) {
        String cardID = params.get("cardID");
        String password = params.get("password");

        // 验证密码
        CardInfo card = cardInfoMapper.findById(cardID);
        if (card == null) {
            return Result.error("银行卡不存在");
        }
        if (!card.getPass().equals(password)) {
            return Result.error("密码错误");
        }

        if (cardInfoMapper.updateReportLoss(cardID, "是") > 0) {
            return Result.success();
        }
        return Result.error("挂失失败");
    }

    /**
     * 修改银行卡密码
     */
    @PostMapping("/change-password")
    public Result<Void> updatePassword(@RequestBody Map<String, String> params) {
        String cardID = params.get("cardID");
        String oldPass = params.get("oldPassword");
        String newPass = params.get("newPassword");
        if (cardInfoMapper.updatePassword(cardID, oldPass, newPass) > 0) {
            return Result.success();
        }
        return Result.error("修改密码失败");
    }

    /**
     * 删除银行卡信息
     */
    @DeleteMapping("/{cardId}")
    public Result<Void> delete(@PathVariable("cardId") String cardId) {
        if (cardInfoMapper.deleteById(cardId) > 0) {
            return Result.success();
        }
        return Result.error("删除失败");
    }

    @GetMapping("/find")
    public Result<CardInfo> findById(@RequestParam String cardID) {
        return Result.success(cardInfoMapper.findById(cardID));
    }

    @GetMapping("/search")
    public Result<List<CardInfo>> search(
            @RequestParam(required = false) String exactCardId,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) BigDecimal minBalance,
            @RequestParam(required = false) BigDecimal maxBalance) {

        if (exactCardId != null && !exactCardId.isEmpty()) {
            // 精确查询
            CardInfo card = cardInfoMapper.findById(exactCardId);
            return Result.success(card != null ? Collections.singletonList(card) : Collections.emptyList());
        } else if (keyword != null && !keyword.isEmpty()) {
            // 模糊查询
            return Result.success(cardInfoMapper.searchByKeyword("%" + keyword + "%"));
        } else if (minBalance != null && maxBalance != null) {
            // 余额范围查询
            return Result.success(cardInfoMapper.findByBalanceRange(minBalance, maxBalance));
        } else {
            // 无查询条件，返回所有数据
            return Result.success(cardInfoMapper.findAll());
        }
    }

    @GetMapping("/balance-range")
    public Result<List<CardInfo>> balanceRange(@RequestParam BigDecimal min, @RequestParam BigDecimal max) {
        return Result.success(cardInfoMapper.findByBalanceRange(min, max));
    }
}